Repeat With (loopVariable) In (list)
In the Repeat With (loopVariable) In (list) form of the Repeat statement, the looping variable is a reference to an item in a list. The number of iterations is equal to the number of items in the list. In the first iteration, the value of the variable isitem 1 of list
(where list is the list you specified in the first line of the statement), in the second iteration, its value isitem 2 of list
, and so on.SYNTAX
repeat with loopVariable in list [ statement ]... end [ repeat ]whereloopVariable is any previously defined variable or a new variable you define in the Repeat statement (see "Notes").
list is a list or a reference (such as
words 1 thru 5
) whose value is a list. list can also be a record; AppleScript coerces the record to a list (see "Notes").statement is any AppleScript statement.
EXAMPLE
The following example numbers the paragraphs of a document with theRepeat With (loopVariable) In (list)
form of the Repeat statement. The value of the referenceparagraphs (the paragraphs of document "List")
is a list of the paragraphs in the document.
tell document "List" set paragraphNum to 1 repeat with n in paragraphs set paragraph paragraphNum to ÿ (paragraphNum as string) & " " & contents of n set paragraphNum to paragraphNum + 1 end repeat end tellNOTES
You can use an existing variable as the looping variable in a Repeat statement or define a new one in the Repeat statement. You cannot change the value of the looping variable in the loop body. The variable is undefined after the loop has been executed, but you can redefine it outside the loop.AppleScript evaluates loopVariable
in list
asitem 1 of list
,item 2 of list
,item 3 of list
, and so on until it reaches the last item in the list:
repeat with i in {1, 2, 3, 4} set x to i end repeat --result: item 4 of {1, 2, 3, 4}To get the value of an item in the list, you must use thecontents of
operator:
repeat with i in {1, 2, 3, 4} set x to contents of i end repeat --result: 4If the value of list is a record, AppleScript coerces the record to a list by stripping the property labels. For example,{a:1, b:2, c:3}
becomes{1, 2, 3}
.